package cloud.provider.payment.controller;


import cloud.provider.payment.service.PayService;
import com.xfanonymous.cloud.entities.Pay;
import com.xfanonymous.cloud.entities.PayDTO;
import com.xfanonymous.cloud.resp.ResultData;
import com.xfanonymous.cloud.resp.ReturnCodeEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @auther xfanonymous
 * @create 2023-12-21 17:34
 *
 * Swagger3
 * 1. @Tag 控制类
 * 2. @Operation Handler方法
 *
 * 1. 所有方法改造为统一返回类型 ResultData
 *
 * Consul
 * 1. @RefreshScope 支持Consul控制台配置动态刷新，程序可以取到最新配置值
 */

@RefreshScope
@RestController
@Slf4j
@Tag(name = "支付微服务模块", description = "支付CRUD")
public class PayController
{
    @Resource
    private PayService payService;

    // 原方法返回String类型
    @PostMapping(value = "/pay/add")
    @Operation(summary = "新增",description = "新增支付流水方法,json串做参数")
    public ResultData<String> addPay(@RequestBody Pay pay)
    {
        System.out.println(pay.toString());
        int i = payService.add(pay);
        return ResultData.success("成功插入记录，返回值: " + i);
        // return "成功插入记录，返回值: " + i;
    }

    // 原方法返回Integer类型
    @DeleteMapping(value = "/pay/del/{id}")
    @Operation(summary = "删除",description = "删除支付流水方法")
    public ResultData<Integer> deletePay(@PathVariable("id") Integer id)
    {
        System.out.println("id ====" + id);
        int i = payService.delete(id);
        return ResultData.success(i);
    }

    // 原方法返回String类型
    @PutMapping(value = "/pay/update")
    @Operation(summary = "修改", description = "修改支付流水方法")
    public ResultData<String> updatePay(@RequestBody PayDTO payDTO)
    {
        Pay pay = new Pay();
        BeanUtils.copyProperties(payDTO, pay);

        int i = payService.update(pay);
        return ResultData.success("成功修改记录，返回值: " + i);
    }

    // 原方法返回List<Pay>类型
    @GetMapping("pay/getall")
    @Operation(summary = "查询", description = "查询全部支付流水")
    public ResultData<List<Pay>> getAll() {
        List<Pay> all = payService.getAll();
        return ResultData.success(all);
    }

    // 原方法返回Pay
    @GetMapping(value = "/pay/get/{id}")
    @Operation(summary = "按照ID查流水", description = "查询支付流水方法")
    public ResultData<Pay> getById(@PathVariable("id") Integer id)
    {
        // 构造查询异常，走全局异常处理
        if(id == -4) throw new RuntimeException("id不能为负数");

//        //暂停62秒钟线程,故意写bug，测试出feign的默认调用超时时间
//        try { TimeUnit.SECONDS.sleep(62); } catch (InterruptedException e) { e.printStackTrace(); }

        Pay pay = payService.getById(id);
        return ResultData.success(pay);
    }

    // 构造异常通过try..catch处理
    @GetMapping(value = "/pay/error")
    public ResultData<Integer> getPayError()
    {
        Integer integer = Integer.valueOf(200);
        try
        {
            System.out.println("come in pay error test");
            int age = 10/0;
        }catch (Exception e){
            e.printStackTrace();
            return ResultData.fail(ReturnCodeEnum.RC500.getCode(), e.getMessage());
        }
        return ResultData.success(integer);
        /** 前端报错：
         * {
         *     "code": "500",
         *     "message": "/ by zero",
         *     "data": null,
         *     "timestamp": 1709717342232
         * }
         * consul报错：java.lang.ArithmeticException: / by zero
         */
    }

    /**
     * 测试Consul分布式配置管理
     * 1. @Value("${server.port}") 获取application.yml中的配置数据
     * 2. @Value("${xfanonymous.consul.info}") 获取http://localhost:8500/
     */
    @Value("${server.port}")
    private String port;

    @Value("${xfanonymous.version}")
    private String version;

    @GetMapping(value = "/pay/get/info")
    public String getInfoByConsul(@Value("${xfanonymous.info}") String consulInfo,
                                  @Value("${xfanonymous.version}") String consulVersion)
    {
        return "consulInfo: " + consulInfo + "\t" + "consulVersion = " + consulVersion + "\n"
                + "port: " + port + "\t" + "version: " + version;
    }

}
